/**
 * @description 列表
 */


import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { message } from "antd"

import http from '@/utils/request';
// import { useLocation } from 'react-router-dom';
import getSearchFields from './src/searchPanel';
import AddComponent from './src/modal-config';
import { $ } from '@/api';
import getColumns from './src/columns-config';
import getTablePropsScorll from './src/scroll-config';
import TableSearchPanel from '@/ui/xx-tableSearchPanel/tableSearchPanel';
import getActionPanel from './src/ActionPanel';
import XxTableModel from '@/ui/xx-table/xx-able';
import resetDataParams from './src/resetDataParams';
import initSearchConfig from './src/initSearchConfig';



const ListView = ({
    listViewRef,
    menuCode,
    buttonList = [],
    setSelectData,
    condition,
    tableCloumns,
    type,
    isInitSerch,
    upDoubleClick = Function,//父组件上（如果有）接收表格数据双击事件，
    upGetChecks = Function,//父组件上（如果有）接收表格check的列表，
    hideSearchPanel = false,//是否隐藏搜索面板;
    hideActionPanel = false,//是否隐藏功能面板
    hidePagination = false,//是否隐藏分页功能
    hideRowSelection = true, //隐藏前面的check选择框
    prentParams = {},
    tablePropsConfig = {}
}) => {


    const [selectedRows, setSelectRows] = useState([]);
    const [state, setState] = useState({
        totalCount: 0,//总共有多少条数据
        data: []
    });




    /**
     * @description 编辑/新建相关窗口
     */
    const [show, setShow] = useState(false)
    const onRef = useRef();
    const [cateTree, setCateTree] = useState([])
    //加载条件和列表
    //本页面需要的表头配置  用来传给表格组件
    const [searchFields, setSearchFields] = useState(getSearchFields({ menuCode, condition }));
    //用来传给表格的加载状态（在请求数据的时候展示用）
    const [loading, setLoading] = useState(false);
    const [params, setParams] = useState({ ...initSearchConfig(searchFields), ...prentParams })
    useEffect(() => {
        if (!isInitSerch) {
            setParams({ ...initSearchConfig(searchFields), ...prentParams })
        }
    }, [searchFields])

    // 删除一条记录
    const onDelete = (object) => {
        http.post({
            url: $.DELETE_API(menuCode),
            params: { ...object },
            before: () => setLoading(true),
            success: (res) => {
                message.success("删除成功")
            },
            failure: () => message.error("删除操作失败"),
            complete: () => getData()
        })
    }



    // 点击了预览
    const onPreview = (object = Object) => {

    }



    // //获取搜索面板上的参数 给到params状态
    const getSearchPanelParams = (val) => {
        setParams({
            ...params,
            ...val
        })
    }






    // 分页器change事件
    const changeCurPage = (pageIndex, pageSize) => {
        setParams({
            ...params,
            pageIndex,
            pageSize
        })
    }



    // 获取数据事件函数
    const getData = () => {
        let object = params;
        http.post({
            url: $.GETLIST_API(menuCode),
            params: resetDataParams({ object, menuCode }),
            before: () => setLoading(true),
            success: ({ data = {} }) => {
                setState({
                    totalCount: data.totalCount,
                    data: data.list
                })
            },
            failure: (error) => {
                message.error(error)
            },
            complete: () => {
                setLoading(false)
                setSelectRows([])
            }
        })
    }
    // 点击编辑按钮
    const onEdit = (record, type) => {
        record['theButtonFlag'] = type | record['theButtonFlag']
        onRef.current.initValue(record)
        setShow(true)
    }


    const [tablePanelConfig, setTabPanelConfig] = useState(getActionPanel({ loading, menuCode, getData, setShow, buttonList, onEdit, onDelete, upGetChecks }).filter(item => item.auth === true))

    useEffect(() => {
        getData()
    }, [params])

    // useEffect(() => {
    //     setState({
    //         data: [],
    //         totalCount: 0
    //     })
    // }, [location.pathname])


    // 新建配置
    const createPorps = {
        onRef,
        getList: getData,
        show,
        setShow,
        // 新建配置 如果是栏目分类，需要重新调整下分类栏目传下去
        cateTree: menuCode === 'menuManage' ? (() => {
            let tree = [
                {
                    menuName: '顶级菜单',
                    menuCode: "0",
                },
                ...state.data
            ]
            return tree
        })() : cateTree

    }



    const [columns, setColumns] = useState(getColumns({ menuCode, onPreview, onEdit, onDelete, buttonList, tableCloumns }))
    useEffect(() => {
        setColumns(getColumns({ menuCode, onPreview, onEdit, onDelete, buttonList, tableCloumns }))
        setSearchFields(getSearchFields({ menuCode, condition }))

        setTabPanelConfig(getActionPanel({ loading, menuCode, getData, setShow, buttonList, onEdit, onDelete, upGetChecks }).filter(item => item.auth === true).filter(item => item.auth === true))

    }, [menuCode, buttonList])


    const onSelectChange = (newSelectedRowKeys, selectedRows) => {
        setSelectRows(selectedRows);
        if (setSelectData) {
            setSelectData(selectedRows);
        }

    }
    const tableProps = {
        hideActionPanel,
        type,
        tablePanelConfig,
        loading,
        columns,
        dataSource: state.data.map((item, index) => ({ ...item, key: index })),
        pagination: {
            pageIndex: params.pageIndex,
            total: state.totalCount,
            pageSize: params.pageSize,
            onChange: changeCurPage
        },
        scroll: getTablePropsScorll({ menuCode }),
        rowSelection: hideRowSelection === true ? false : {
            selectedRowKeys: selectedRows.map(item => item.key),
            onChange: onSelectChange,
            ...tablePropsConfig.rowSelection
        },
        // 新加 适应新表格
        rowKey: 'key',
        selectRecords: selectedRows,
        // 双击事件
        onRowDoubleClick: (record, index) => {
            upDoubleClick && upDoubleClick(record, index)
        }
    }

    // 向外暴露方法 设置参数
    useImperativeHandle(listViewRef, () => ({
        params,
        getParams: () => ({
            ...params
        }),
        setParams
    }));
    return (
        <>
            <div style={{
                display: 'flex',
                flexDirection: "column",
                width: '100%',
                padding: 10
            }}>
                <AddComponent menuCode={menuCode} createPorps={createPorps} />
                <TableSearchPanel
                    fields={searchFields}
                    params={params}
                    onSearch={getSearchPanelParams}
                />
                <XxTableModel {...tableProps} />
            </div>

        </>
    )

}
export default ListView;